package com.zh.client.user.controller;

import com.zh.client.user.service.UserService;
import com.zh.pojo.Orderitem;
import com.zh.pojo.Orders;
import com.zh.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/client/user")
public class UserController {
    @Autowired
    UserService userService;

    @RequestMapping("/register")
    public String register(User user, String checkCode, Model model, HttpServletRequest request) {
        model.addAttribute("user",user);
        String checkcode_session = (String) request.getSession().getAttribute("checkcode_session");
        if(checkCode.equals(checkcode_session)){
            user.setActiveCode(UUID.randomUUID().toString());
            int rows = userService.addUser(user,request);
            if(rows > 0){
                return "client/registersuccess";
            }else {
                model.addAttribute("fail","用户注册失败，请重试！");
                return "client/register";
            }
        }else {
            model.addAttribute("check_error","校验码错误，请重新输入！");
            return "client/register";
        }
    }

    //用户激活
    @RequestMapping("/activeUser")
    public String activeUser(String activeCode){
        int rows = userService.activeUser(activeCode);
        if(rows > 0){
            return "redirect:/client/activesuccess.jsp";
        }else {
            return "redirect:/client/activefail.jsp";
        }
    }

    //判断邮箱是否存在
    @RequestMapping("/findemail")
    @ResponseBody
    public String findmail(String email){
        int rows = userService.findmail(email);
        if(rows > 0){
            return "OK";
        }else {
            return "FAIL";
        }
    }

    //判断会员名是否存在
    @RequestMapping("/findusername")
    @ResponseBody
    public String findusername(String username){
        int rows = userService.findusername(username);
        if(rows > 0){
            return "OK";
        }else {
            return "FAIL";
        }
    }

    //账户登录页面
    @RequestMapping("/myAccount")
    public String myAccount(HttpServletRequest request){
        User user = (User) request.getSession().getAttribute("Login_user");
        if(user == null){
            //自动登录
            user = autologin(request);
            if(user != null){
                request.getSession().setAttribute("Login_user",user);
                return "client/myAccount";
            }else {
                return "client/login";
            }
        }else {
            return "client/myAccount";
        }
    }

    //自动登录
    public User autologin(HttpServletRequest request) {
        String username = null;
        String password = null;
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if("bookstore_username".equals(cookie.getName())){
                username = cookie.getValue();
            }
            if("bookstore_password".equals(cookie.getName())){
                password = cookie.getValue();
            }
        }
        User user = new User();
        user.setPassword(password);
        user.setUsername(username);
        return userService.findUserByLogin(user);
    }

    //用户登录页面
    @RequestMapping("/login")
    public String login(User user, HttpServletRequest request, HttpServletResponse response, String remember, String autologin){
        User user1 = userService.findUserByLogin(user);
        if(user1 != null){
            if(user1.getState() == 1){
                if("1".equals(autologin)){
                    addCookie(autologin,user,request,response);
                }else if("1".equals(remember)){
                    addCookie(autologin,user,request,response);
                }
                request.getSession().setAttribute("Login_user",user1);
                return "client/myAccount";
            }else {
                request.setAttribute("Login_error","用户未激活，请激活后再登录！");
                return "client/login";
            }
        }else {
            request.setAttribute("Login_error","用户名或密码错误，请重新登录！");
            return "client/login";
        }
    }

    //保存用户信息存入cookie
    private void addCookie(String autologin, User user, HttpServletRequest request, HttpServletResponse response) {
        Cookie cookie = new Cookie("bookstore_username",user.getUsername());
        //保存时间
        cookie.setMaxAge(60*60*24);
        //cookie的作用域
        cookie.setPath(request.getContextPath()+"/");
        //把定义好的cookie响应客户端
        response.addCookie(cookie);
        if("1".equals(autologin)){
            Cookie cookie1 = new Cookie("bookstore_password",user.getPassword());
            cookie1.setMaxAge(60*60*24);
            //cookie的作用域
            cookie1.setPath(request.getContextPath()+"/");
            //把定义好的cookie响应客户端
            response.addCookie(cookie1);
        }
    }

    //用户退出
    @RequestMapping("/logout")
    public String logout(Model model,HttpServletRequest request, HttpServletResponse response){
        request.getSession().removeAttribute("Login_user");
        model.addAttribute("Login_error","用户退出成功，请重新登录！");
        Cookie cookie = new Cookie("bookstore_username",null);
        cookie.setMaxAge(0);
        cookie.setPath(request.getContextPath()+"/");
        response.addCookie(cookie);
        Cookie cookie1 = new Cookie("bookstore_password",null);
        cookie1.setMaxAge(0);
        //cookie的作用域
        cookie1.setPath(request.getContextPath()+"/");
        //把定义好的cookie响应客户端
        response.addCookie(cookie1);
        return "client/login";
    }

    //用户信息修改
    @RequestMapping("/modifyUser")
    public String modifyUser(User user,HttpServletRequest request, Model model){
        User login_user = (User) request.getSession().getAttribute("Login_user");
        user.setId(login_user.getId());
        int rows = userService.modifyUser(user);
        if(rows > 0){
            model.addAttribute("Login_error","用户信息修改成功，请重新登录！");
            return "client/login";
        }else {
            model.addAttribute("fail","用户信息修改失败，请重试！");
            return "client/modifyuserinfo";
        }
    }

    //查询登录用户的所有订单
    @RequestMapping("/findOrderByUser")
    public String findOrderByUser(HttpSession session, Model model){
        User login_user = (User) session.getAttribute("Login_user");
        List<Orders> orders = userService.findOrderByUser(login_user.getId());
        model.addAttribute("orders",orders);
        return "client/orderlist";
    }

    //查看订单详细信息
    @RequestMapping("/findOrderById")
    public String findOrderById(String id, Model model){
        List<Orderitem> items = userService.findOrderitemById(id);
        model.addAttribute("items",items);
        return "client/orderInfo";
    }

    //删除订单信息
    @RequestMapping("/removeOrderById")
    public String removeOrderById(String id, String flag){
        userService.removeOrderById(id,flag);
        return "redirect:/client/user/findOrderByUser";
    }
}
